import SingleBase from '../base/SingleBase';


let localStorage = cc.sys.localStorage;
export default class LocalStorage extends SingleBase {

    setItem(key: string, value: string | number) {
        localStorage.setItem(key, value);
    }
    getItem(key: string): string {
        let data = localStorage.getItem(key);
        if (!data) {
            return '';
        }
        return data + '';
    }
    getItemNumber(key: string): number {
        let data = localStorage.getItem(key);
        if (!data) {
            return 0;
        }
        return Number(data);
    }
    clear(...keys: string[]) {
        if (!keys) {
            localStorage.clear();
            return;
        }
        keys.forEach(value => {
            localStorage.removeItem(value);
        })
    }
    getItemMap(name: string, key?: string | number): {key, value, times} {
        let data = localStorage.getItem(name) || '{}';
        data = JSON.parse(data);
        if (typeof key !== 'undefined') {
            return data[key] || {};
        }
        return data;
    }
    setItemMap(name: string, {key, value}) {
        let data = this.getItemMap(name);
        let item = data[key] || {};
        let count = item.value || 0;
        let times = item.times || 0;
        times ++;
        if (times >= 2) {
            times = 0;
            count += value;
        }
        item = {value: count, times};
        data[key] = item;
        localStorage.setItem(name, JSON.stringify(data));
    }
    setItemList(name: string, {key, value}) {
        let data = this.getItemList(name);
        let count = data[key] || 0;
        count += value;
        data[key] = count;
        localStorage.setItem(name, JSON.stringify(data));
    }
    getItemList(name: string, key?: string | number): number[] | object {
        let data = localStorage.getItem(name) || '{}';
        data = JSON.parse(data);
        if (key) {
            return data[key] || 0;
        }
        return data;
    }

    getSkinArr(name:string) : Array<any>{
        let data = localStorage.getItem(name) ||'[1,1,0,0,0,0,0,0]';
        data = JSON.parse(data);
        if(data.length < 8){
            for(; data.length < 8;){
                data.push(0);
            }
        }
        return data;
    }

    setItemArr(name:string, arr){
        localStorage.setItem(name, JSON.stringify(arr));
    }
}